using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// Agent决策引擎接口
    /// </summary>
    public interface IAgentDecisionEngine
    {
        /// <summary>
        /// 制定决策
        /// </summary>
        Task<string> MakeDecisionAsync(string agentId, string context);

        /// <summary>
        /// 获取决策历史
        /// </summary>
        Task<List<string>> GetDecisionHistoryAsync(string agentId, int maxResults = 50);
    }

    /// <summary>
    /// Agent决策引擎实现
    /// </summary>
    public class AgentDecisionEngine : IAgentDecisionEngine
    {
        private readonly ILogger<AgentDecisionEngine> _logger;
        private readonly Dictionary<string, List<string>> _decisionHistory = new();

        public AgentDecisionEngine(ILogger<AgentDecisionEngine> logger)
        {
            _logger = logger;
        }

        public async Task<string> MakeDecisionAsync(string agentId, string context)
        {
            try
            {
                _logger.LogInformation($"Agent {agentId} 开始决策: {context}");

                // 简化的决策逻辑
                var decision = $"基于上下文 '{context}'，建议采取以下行动：分析问题、制定计划、执行方案。";

                // 记录决策历史
                if (!_decisionHistory.ContainsKey(agentId))
                {
                    _decisionHistory[agentId] = new List<string>();
                }
                _decisionHistory[agentId].Add(decision);

                _logger.LogInformation($"Agent {agentId} 决策完成");
                return decision;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Agent {agentId} 决策失败");
                return $"决策失败: {ex.Message}";
            }
        }

        public async Task<List<string>> GetDecisionHistoryAsync(string agentId, int maxResults = 50)
        {
            try
            {
                if (_decisionHistory.TryGetValue(agentId, out var history))
                {
                    return history.TakeLast(maxResults).ToList();
                }
                return new List<string>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取决策历史失败: Agent {agentId}");
                return new List<string>();
            }
        }
    }
}
